package util

import (
	"crypto/md5"
	"encoding/binary"
	"encoding/hex"
	"fmt"
	"time"
)

const aesKEY = "abcdefghijklmnlp"
const md5Len = 4

func GenSessionId(userId int64) string {
	return fmt.Sprintf("%d-%d-%s",
		userId, time.Now().Unix(), RandNumStr(6))
}

func GenUserAuthToken(uid int64) (
	accessToken, refreshToken string, err error) {
	accessToken, err = GenAccessToken(uid)
	if err != nil {
		return
	}

	refreshToken, err = genFrefreshToken(uid)
	if err != nil {
		return
	}
	return

}

func GenAccessToken(uid int64) (string, error) {
	byteInfo := make([]byte, 12)
	binary.BigEndian.PutUint64(byteInfo, uint64(uid))
	binary.BigEndian.PutUint32(byteInfo[8:], uint32(time.Now().UnixNano()))
	encodeByte, err := AesEncrypt(byteInfo, []byte(aesKEY))
	if err != nil {
		return "", err
	}
	md5Byte := md5.Sum(encodeByte)
	data := append(md5Byte[0:md5Len], encodeByte...)
	return hex.EncodeToString(data), nil

}

func genFrefreshToken(userId int64) (string, error) {
	return GenAccessToken(userId)
}
